<template>
  <div class="project">
    <div class="main">
      <div class="header">
        <el-form :inline="true">
          <el-form-item label="标题">
            <el-input placeholder="请输入标题" v-model="findProjectQuery.title"></el-input>
          </el-form-item>
          <el-form-item label="状态">
            <el-select placeholder="请选择状态" v-model="findProjectQuery.status">
              <el-option label="启用" value="1"></el-option>
              <el-option label="禁用" value="0"></el-option>
              <el-option label="草稿" value="3"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="findProjectInfo">查询</el-button>
            <el-button @click="replace">重置</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="success" @click="router.push(`/addProject/${-1}`)">
              <el-icon><Plus /></el-icon>
              <span>新增项目</span>
            </el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="danger" @click="deleteBatch">
              <el-icon><Minus /></el-icon>
              <span>批量删除</span>
            </el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="body" v-if="projectList.length > 0">
        <el-table :data="projectList" stripe @selection-change="handleSelectionnChange">
          <el-table-column type="selection"> </el-table-column>
          <el-table-column label="标题" prop="title" show-overflow-tooltip></el-table-column>
          <el-table-column label="标签" width="100">
            <template #default="scope">
              <el-tag v-for="item in scope.row.tags" :key="item.id">{{ item.name }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="评论数量" prop="commentCount"></el-table-column>
          <el-table-column label="点赞数量" prop="likeCount"></el-table-column>
          <el-table-column label="是否置顶" prop="isTop">
            <template #default="scope">
              <span
                :class="scope.row.isTop === 0 ? 'blue' : 'red'"
                @click="updateStatus('a', scope.row.isTop === 0 ? 1 : 0, scope.row.id)"
                >{{ scope.row.isTop === 0 ? '置顶' : '取消置顶' }}</span
              >
            </template>
          </el-table-column>
          <el-table-column label="更新状态" prop="latest">
            <template #default="scope">
              <span
                :class="scope.row.latest === 0 ? 'blue' : 'red'"
                @click="updateStatus('b', scope.row.latest === 0 ? 1 : 0, scope.row.id)"
              >
                {{ scope.row.latest === 0 ? '最近更新' : '取消最近更新' }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="状态" prop="status">
            <template #default="scope">
              <span
                :class="computedStatusColor(scope.row.status)"
                @click="updateStatus('c', scope.row.status === 0 ? 1 : 0, scope.row.id)"
                >{{ computedStatus(scope.row.status) }}</span
              >
            </template>
          </el-table-column>
          <el-table-column
            label="创建时间"
            prop="createTime"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            label="修改时间"
            prop="updateTime"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column label="操作" width="130">
            <template #default="scope">
              <el-button
                :text="true"
                type="primary"
                size="small"
                @click="router.push(`/addProject/${scope.row.id}`)"
                >编辑</el-button
              >
              <el-button :text="true" type="danger" size="small" @click="deleteById(scope.row.id)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-empty v-else></el-empty>
      <div class="page">
        <el-pagination
          :total="total"
          v-model:current-page="findProjectQuery.page"
          v-model:page-size="findProjectQuery.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handlePageSizeChange"
          @current-change="handlePageChange"
        ></el-pagination>
      </div>
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref } from 'vue'
import { Plus, Minus } from '@element-plus/icons-vue'
import { deleteBatchService, getProjectListService, updateStatusBatchService } from '@/api/Peoject'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'

const router = useRouter()

const total = ref(null)
const projectList = ref([{}])
const findProjectQuery = ref({
  page: 1,
  pageSize: 9,
  title: '',
  status: null,
})

/**
 * 修改项目状态字段
 * @param chart
 * @param status
 */
const statusQuery = ref({
  id: null,
  isTop: null,
  latest: null,
  status: null,
})
const updateStatus = (chart, status, id) => {
  statusQuery.value.id = id
  switch (chart) {
    case 'a':
      // 修改置顶状态
      console.log('修改置顶状态:', status)
      statusQuery.value.isTop = status
      updateStatusBatchService(statusQuery.value).then(() => {
        getProjectList(findProjectQuery.value)
        statusQuery.value = {
          id: null,
          isTop: null,
          latest: null,
          status: null,
        }
      })
      break
    case 'b':
      // 修改更新状态
      console.log('修改更新状态:', status)
      statusQuery.value.latest = status
      updateStatusBatchService(statusQuery.value).then(() => {
        getProjectList(findProjectQuery.value)
      })
      break
    case 'c':
      // 修改状态
      console.log('修改状态:', status)
      statusQuery.value.status = status
      updateStatusBatchService(statusQuery.value).then(() => {
        getProjectList(findProjectQuery.value)
      })
      break
  }
}

// 删除
const projectIds = ref([])
const deleteById = (id) => {
  ElMessageBox.confirm('你确认删除该条数据吗?', 'Warning', {
    type: 'warning',
    confirmButtonText: '确认',
    cancelButtonText: '取消',
  })
    .then(() => {
      projectIds.value.push(id)
      deleteBatchService(projectIds.value).then(() => {
        projectIds.value = projectIds.value.filter((item) => item !== id)
        getProjectList(findProjectQuery.value)
      })
    })
    .catch(() => {
      ElMessage.success('取消删除')
    })
}
const handleSelectionnChange = (row) => {
  const obj = JSON.parse(JSON.stringify(row))
  projectIds.value = []
  obj.forEach((item) => {
    projectIds.value.push(item.id)
  })
}
// 批量删除
const deleteBatch = () => {
  if (projectIds.value.length === 0) {
    ElMessage.error('暂未选中数据')
    return false
  }
  ElMessageBox.confirm(`你确认删除这${projectIds.value.length}条数据`, 'Warning', {
    type: 'warning',
    confirmButtonText: '确认',
    cancelButtonText: '取消',
  })
    .then(() => {
      deleteBatchService(projectIds.value).then(() => {
        getProjectList(findProjectQuery.value)
        projectIds.value = []
      })
    })
    .catch(() => {
      ElMessage.success('取消删除')
    })
}

// 计算状态字段
const computedStatus = (status) => {
  if (status === 1) {
    return '禁用'
  } else if (status === 0) {
    return '启用'
  } else {
    return '草稿'
  }
}
const computedStatusColor = (status) => {
  if (status === 1) {
    return 'red'
  } else if (status === 0) {
    return 'blue'
  } else {
    return 'green'
  }
}

// 查询项目数据
const findProjectInfo = () => {
  getProjectList(findProjectQuery.value)
}
// 重置
const replace = () => {
  getProjectList({
    page: 1,
    pageSize: 9,
    title: '',
    status: null,
  })
}

/**
 * 分页查询
 */
const handlePageChange = (page) => {
  findProjectQuery.value.page = page
  getProjectList(findProjectQuery.value)
}
const handlePageSizeChange = (pageSize) => {
  findProjectQuery.value.pageSize = pageSize
  getProjectList(findProjectQuery.value)
}

/**
 * 获取项目数据
 * @param query
 */
const getProjectList = async (query) => {
  const { data } = await getProjectListService(query)
  total.value = data.total
  projectList.value = data.records
}
onMounted(() => {
  getProjectList(findProjectQuery.value)
})
</script>

<style lang="scss" scoped>
.project {
  padding: 15px;
  background-color: #f3f4f5;

  .main {
    min-height: 100vh;
    padding: 20px;
    background-color: #fff;
    border-radius: 7px;

    .header {
      :deep(.el-select__wrapper) {
        width: 150px;
      }
    }

    .page {
      margin-top: 20px;
      display: flex;
      justify-content: center;
    }
  }
}

.blue {
  cursor: pointer;
  color: #37b4fd;
}
.red {
  cursor: pointer;
  color: red;
}
.green {
  color: #43e478;
  pointer-events: none;
}

::v-deep.el-table .cell {
  text-align: center !important;
}
</style>